<template>
	<div>
		<div>{{ piniaA.msg }}</div>
		<div>{{ piniaB.msg }}</div>
		<div>{{ msg }}</div>
		<button @click="change">直接修改</button>
		<button @click="changeByPatch">$patch修改</button>
		<button @click="reset">重置PiniaA模块</button>
		<button @click="changeByAction">调用action修改</button>
	</div>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { usePiniaAStore } from '@/store/piniaA'
import { usePiniaBStore } from '@/store/piniaB'
import { usePiniaCStore } from '@/store/piniaC'

const piniaA = usePiniaAStore()
const piniaB = usePiniaBStore()
const piniaC = usePiniaCStore()

// TODO const { msg } = PiniaC(); 直接结构将失去响应，采用 storeToRefs
const { msg } = storeToRefs(piniaC)

const change = () => {
	// 直接修改
	piniaA.msg = 'A'
	piniaB.msg = 'B'
	msg.value = 'C'
}
const changeByPatch = () => {
	// 通过对象修改
	piniaA.$patch({
		msg: 'AA',
	})
	// 通过函数修改
	piniaB.$patch((state) => {
		state.msg = 'BB'
	})
}

// 通过整个对象修改，必须传入每个属性 ，不常用
// piniaA.$state = { msg: '', };

// 通过action修改
const changeByAction = () => {
	piniaA.changeMsg('123')
}

const reset = () => {
	// TODO 重置pinia setup方式的store需要自己实现 $reset 方法
	piniaA.$reset()
}

// 监听 state,任何值改变都会触发
piniaA.$subscribe(
	(args, state) => {
		console.log('$subscribe==========', { args, state })
	},
	{
		//配置
	}
)
// 监听 action,任何action调用都会触发 , 第二参数为true时，组件销毁继续监听
piniaA.$onAction((args) => {
	console.log('$onAction=======', args)
}, true)
</script>

<style scoped></style>
